import os
import math
import cmath

# I directly use function from opencv-python
# it is not a good solution since the user has to install opencv-python
# a better method is to use scipy to fit

try:
    import cv2 as cv
    import numpy as np
except ModuleNotFoundError:
    os.system("pip install opencv-python")
    import cv2 as cv
    import numpy as np

try:
    import openpyxl
except ModuleNotFoundError:
    os.system("pip install openpyxl")
    import openpyxl

try:
    import matplotlib.pyplot as plt
    from matplotlib.patches import Ellipse
except ModuleNotFoundError:
    os.system("pip install matplotlib")
    import matplotlib.pyplot as plt
    from matplotlib.patches import Ellipse

if __name__ == "__main__":
    # load Excel file
    fileName = input("please input file name of you excel file\n")
    wkbook = openpyxl.load_workbook(fileName)
    sht = wkbook["Sheet1"]
    
    fig = plt.figure()

    # Load data
    for r in range(1, 8):
        pts = []
        p = []
        for i, c in enumerate(range(0, 360, 30)):
            cellindex = chr(ord('A') + i + 1) + str(r + 1)
            comp = cmath.rect(int(sht[cellindex].value), math.radians(c))
            print(int(sht[cellindex].value))
            x, y = comp.real, comp.imag
            pts.append(((x, y), ))
        
        # Fit Ellipse with opencv functions (fitEllipse / fitEllipseDirect / fitEllipseAMS)
        pts = np.array(pts, np.float32)
        elli = cv.fitEllipseDirect(pts)
        
        ax = fig.add_subplot(240 + r, aspect='equal')
        ax.axis((-1200, 1200, -1200, 1200))
        ax.add_patch(Ellipse(elli[0], elli[1][0], elli[1][1], elli[2]))
        for _ in p:
            ax.scatter(_[0], _[1])
        
        print(elli)
    
    plt.show()